package com.api.shuigui.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import weaver.general.BaseBean;
import weaver.general.GCONST;

import javax.imageio.stream.FileImageOutputStream;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 读取压缩包中的图片到指定目录
 */
public class DocUtil {

    /**
     * 指定文件压缩包转存到指定路径
     *
     * @param file     文件绝对路径
     * @param name     文件名
     * @param rename   文件保存后名字
     * @param savePath 保存路径
     * @return 转存后的文件地址
     * @throws IOException IO异常
     */
    public static String readZipFile(String file, String name, String rename, String savePath) throws IOException {
        InputStream in = Files.newInputStream(Paths.get(file));
        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry ze;
        String e_category = GCONST.getRootPath();
        String imgname = "";
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.isDirectory()) {
            } else {
                //获取读取到得文件名, 使用压缩包中的文件名字作为自己的文件名
                if ("".equals(rename)) {
                    imgname = name;
                } else {
                    imgname = rename;
                }
                //如果zip中的是文件
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] array = new byte[1024];
                int num;
                while ((num = zin.read(array, 0, array.length)) > -1) {
                    byteArrayOutputStream.write(array, 0, num);
                }
                byte[] bytes = byteArrayOutputStream.toByteArray();
                String filepath = e_category + savePath;
                File f = new File(filepath);
                //如果路径不存在，则创建路径
                if (!f.exists()) {
                    f.mkdirs();
                }
                //将图片写入对于的文件夹下
                FileImageOutputStream imageOutput = new FileImageOutputStream(new File(filepath + "/" + imgname));
                imageOutput.write(bytes, 0, bytes.length);
                imageOutput.flush();
                imageOutput.close();

            }
        }
        zin.closeEntry();
        //返回处理好的路径
        return "/" + savePath + imgname;
    }

    /**
     * 利用正则表达式替换img中的src值
     *
     * @param str  html内容
     * @param path 需要替换的标签
     * @return
     */
    public static String replaceHtmlTag(String str, String path) {
        String regxpForTag = "<\\s*img\\s+([^>]*)\\s*";
        String regxpForTagAttrib = "src=\"/weaver/weaver.file.FileDownload?\\s*([^\"]+)\"";
        String tag = "src=\"" + path + "\"";
        Pattern patternForTag = Pattern.compile(regxpForTag, Pattern.CASE_INSENSITIVE);
        Pattern patternForAttrib = Pattern.compile(regxpForTagAttrib, Pattern.CASE_INSENSITIVE);
        Matcher matcherForTag = patternForTag.matcher(str);
        StringBuffer sb = new StringBuffer();
        boolean result = matcherForTag.find();
        while (result) {
            //查找多次，直到找到并替换
            StringBuffer sbreplace = new StringBuffer("<img ");
            Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag.group(1));
            String attributeStr = null;
            if (matcherForAttrib.find()) {
                attributeStr = matcherForAttrib.group(0);
                matcherForAttrib.appendReplacement(sbreplace, tag);
            }
            matcherForAttrib.appendTail(sbreplace);
            matcherForTag.appendReplacement(sb, sbreplace.toString());
            if (attributeStr != null) {
                break;
            }
            result = matcherForTag.find();
        }
        matcherForTag.appendTail(sb);
        return sb.toString();
    }

    /**
     * 提取html body标签中的内容
     *
     * @param content
     */
    public static String ReplaceHtmlBody(String content) {
        //将string文本转换成html文本
        Document doc = Jsoup.parse(content);
        return doc.body().children().outerHtml();
    }

    public static String ContentIsImgurl(String content) {
        try {
            Pattern compile;
            compile = Pattern.compile("<img.*?>", Pattern.CASE_INSENSITIVE);
            Matcher matcher = compile.matcher(content); // string：后台返的内容，图片就是从中提取的
            if (matcher.find()) {
                String img = matcher.group(0);
                Matcher m = Pattern.compile("\"http?(.*?)(\"|>|\\s+)").matcher(img);
                m.find();
                String url = m.group();
                return url.substring(1, url.length() - 1);
            }
        } catch (Exception e) {
            new BaseBean().writeLog(e.getMessage());
            return "";
        }
        return "";

    }

    /**
     * 判断文件是否存在
     *
     * @param name     文件名
     * @param savePath 路径
     * @return 是否存在
     */
    public static boolean isCategoryByName(String name, String savePath) {
        String e_category = GCONST.getRootPath();
        String path = e_category + savePath + name;
        File file = new File(path);
        //如果存在这个文件
        return file.exists();
    }
}
